//
//  JXSegmentedView+Rx.swift
//  NovaRings
//
//  Created by 李然 on 2023/3/1.
//

import Foundation
import JXSegmentedView
import RxSwift
import RxCocoa

extension Reactive where Base: JXSegmentedView {
    
    var delegate: RxJXSegmentedViewDelegateProxy {
        return RxJXSegmentedViewDelegateProxy.proxy(for: base)
    }

    public var selectedItem: Observable<Int> {
        return delegate.selectedItem.asObservable()
    }
}

class RxJXSegmentedViewDelegateProxy: DelegateProxy<JXSegmentedView, JXSegmentedViewDelegate>, DelegateProxyType, JXSegmentedViewDelegate {
    
    weak private(set) var segmentedView: JXSegmentedView?
    
    fileprivate let selectedItem = BehaviorRelay<Int>(value: 0)
    
    init(segmentedView: ParentObject) {
        self.segmentedView = segmentedView
        super.init(parentObject: segmentedView, delegateProxy: RxJXSegmentedViewDelegateProxy.self)
    }
    
    static func registerKnownImplementations() {
        self.register {
            RxJXSegmentedViewDelegateProxy(segmentedView: $0)
        }
    }
    
    static func currentDelegate(for object: JXSegmentedView) -> JXSegmentedViewDelegate? {
        return object.delegate
    }
    
    static func setCurrentDelegate(_ delegate: JXSegmentedViewDelegate?, to object: JXSegmentedView) {
        object.delegate = delegate
    }
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        selectedItem.accept(index)
    }
}
